<!DOCTYPE html>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<style>
#box {
  position: relative;
  height: 100px;
  width: 100px;
  background-color: blue;
  transition-delay: 0.3s;
  transition-duration: 0.7s;
  transition-property: width;
  transition-timing-function: linear;
}

#box.target, #box:hover {
  width: 200px;
}
</style>
<div id="box"></div>
<script>
function assert_px_approx_equals(actual, expected, epsilon, description) {
  var match = /^([\d.]+)px$/.exec(actual);
  assert_not_equals(match, null);
  assert_approx_equals(Number(match[1]), expected, epsilon, description);
}

test(function() {
  var box = document.getElementById('box');

  assert_equals(getComputedStyle(box).width, '100px', 'initial width');

  // Start the animation.
  box.className = 'target';
  getComputedStyle(box).width;  // Force the transition.
  var animation = box.getAnimations()[0];
  animation.pause();

  animation.currentTime = 0;
  assert_equals(getComputedStyle(box).width, '100px', 'width at transition start');
  animation.currentTime = 300;
  assert_equals(getComputedStyle(box).width, '100px', 'width after delay');
  animation.currentTime = 700;
  assert_px_approx_equals(getComputedStyle(box).width, 157.141, 0.01, 'width mid-forward');

  // Reverse the animation.
  box.className = '';
  getComputedStyle(box).width;  // Force the transition.
  animation = box.getAnimations()[0];
  animation.pause();  // The animation is replaced, so pause it again.

  animation.currentTime = 0;
  assert_px_approx_equals(getComputedStyle(box).width, 157.141, 0.01, 'width after className');
  animation.currentTime = 300;
  assert_px_approx_equals(getComputedStyle(box).width, 157.141, 0.01, 'width after second delay');
  animation.currentTime = 500;
  assert_px_approx_equals(getComputedStyle(box).width, 128.562, 0.01, 'width mid-reverse');

  // Go forward again.  This tests the reversingAdjustedStartValue is set
  // properly the first time it's reversed.
  box.className = 'target';
  getComputedStyle(box).width;  // Force the transition.
  animation = box.getAnimations()[0];
  animation.pause();  // The animation is replaced, so pause it again.

  animation.currentTime = 0;
  assert_px_approx_equals(getComputedStyle(box).width, 128.562, 0.01, 'width after second reverse');
  animation.currentTime = 300;
  assert_px_approx_equals(getComputedStyle(box).width, 128.562, 0.01, 'width at transition start');
  animation.currentTime = 700;
  assert_px_approx_equals(getComputedStyle(box).width, 185.703, 0.01, 'width mid-second-reverse');
  animation.currentTime = 1100;
  assert_equals(getComputedStyle(box).width, '200px', 'width at end');

  assert_equals(box.getAnimations().length, 0, 'animation ended');

}, "Check that reversing a transition (with positive delay) mid-way adjusts the duration");
</script>
